package com.test.followme;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.test.utilities.Utility;

public class RegId
{
	String regid;
	Context context;
	private GoogleCloudMessaging gcm;
	private AtomicInteger msgId = new AtomicInteger();
	
	public RegId(Context con)
	{
		context = con;
		gcm = GoogleCloudMessaging.getInstance(context);
	}
	
	public String getRegid()
	{
		return regid;
	}
	
	public boolean checkPlayServices()
	{
		int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
		if (resultCode != ConnectionResult.SUCCESS)
		{
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
			{
				//GooglePlayServicesUtil.getErrorDialog(resultCode, context, Globals.PLAY_SERVICES_RESOLUTION_REQUEST).show();
			}
			else
			{
				Log.i(Globals.TAG, "This device is not supported.");
				//finish();
			}
			return false;
		}
		return true;
	}
	
	private static int getAppVersion(Context context)
	{
		try
		{
			PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionCode;
		}
		catch (NameNotFoundException e)
		{
			throw new RuntimeException("Could not get package name: " + e);
		}
	}
	
	public void register2GCM()
	{
		if (checkPlayServices())
		{
			regid = Utility.getSharedPrefs(context, Globals.PREFS_REG_ID);
			if (TextUtils.isEmpty(regid))
			{
				registerInBackground();
			}
			
		}
		else
		{
			Log.i(Globals.TAG, "No valid Google Play Services APK found.");
		}
	}
	
	/**
	 * Registers the application with GCM servers asynchronously.
	 * <p>
	 * Stores the registration ID and the app versionCode in the application's
	 * shared preferences.
	 */
	private void registerInBackground()
	{
		new AsyncTask<Void, Void, String>()
		{
			@Override
			protected String doInBackground(Void... params)
			{
				String msg = "";
				try
				{
					if (gcm == null)
					{
						gcm = GoogleCloudMessaging.getInstance(context);
					}
					regid = gcm.register(Globals.GCM_SENDER_ID);
					msg = "Device registered, registration ID=" + regid;
					
					sendRegistrationIdToBackend();
					
					Utility.addSharedPrefs(context, Globals.PREFS_REG_ID, regid);
				}
				catch (IOException ex)
				{
					msg = "Error :" + ex.getMessage();
				}
				return msg;
			}
		}.execute(null, null, null);
	}
	
	/**
	 * Sends the registration ID to the 3rd party server via an upstream GCM
	 * message. Ideally this would be done via HTTP to guarantee success or
	 * failure immediately, but it would require an HTTP endpoint.
	 */
	private void sendRegistrationIdToBackend()
	{
		Log.d(Globals.TAG, "REGISTER USERID: " + regid);
		String name = "";
		new AsyncTask<String, Void, String>()
		{
			@Override
			protected String doInBackground(String... params)
			{
				String msg = "";
				try
				{
					Bundle data = new Bundle();
					data.putString("name", params[0]);
					data.putString("action", "com.test.followme.REGISTER");
					String id = Integer.toString(msgId.incrementAndGet());
					gcm.send(Globals.GCM_SENDER_ID + "@gcm.googleapis.com", id, Globals.GCM_TIME_TO_LIVE, data);
					msg = "Sent registration";
				}
				catch (IOException ex)
				{
					msg = "Error :" + ex.getMessage();
				}
				return msg;
			}
			
			@Override
			protected void onPostExecute(String msg)
			{
				Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
			}
		}.execute(name);
	}
	
	/**
	 * Stores the registration ID and the app versionCode in the application's
	 * {@code SharedPreferences}.
	 * 
	 * @param context
	 *            application's context.
	 * @param regId
	 *            registration ID
	 */
//	private void storeRegistrationId(Context context, String regId)
//	{
//		final SharedPreferences prefs = getGcmPreferences(context);
//		int appVersion = getAppVersion(context);
//		Log.i(Globals.TAG, "Saving regId on app version " + appVersion);
//		SharedPreferences.Editor editor = prefs.edit();
//		editor.putString(Globals.PREFS_PROPERTY_REG_ID, regId);
//		editor.putInt(Globals.PROPERTY_APP_VERSION, appVersion);
//		editor.commit();
//	}
}
